/**
 * Copyright (c) 2013 onionframework.org
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package org.onionframework.core.optional;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.onionframework.core.Framework;
import org.onionframework.core.components.ComponentDescriptor;
import org.onionframework.core.components.OptionalPart;
import org.onionframework.core.config.SystemConfig;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.xml.BeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.core.io.Resource;
import org.w3c.dom.Element;

public class OptionalPartParser implements BeanDefinitionParser {

	@Override
	public BeanDefinition parse(Element element, ParserContext parserContext) {
		for(ComponentDescriptor component : Framework.getComponents()){
			for(OptionalPart optional : component.getOptionalParts())
				this.processOptional(element, optional.getId(), optional.getLocation(), parserContext);
		}
		
		return null;
	}
	
	private void processOptional(Element element, String id, String location, ParserContext parserContext){
		Resource[] resources = null;
		String[] locations = null;
		
		if(StringUtils.isNotBlank(location)){
			resources = ImportBeanDefinitionParser.resolveResources(element, location, parserContext);
			locations = new String[resources.length];
			String helper;
			
			for(int i = 0; i < resources.length; i++){
				location = resources[i].toString();
				if(location.indexOf(".jar!/") > 0){
					helper = location.substring(location.indexOf(".jar!/"));
					locations[i] = location.substring(helper.lastIndexOf('/') + 1);
				}else{
					locations[i] = location;
				}
			}
		}
		
		if(SystemConfig.Config.getBoolean(id,false)){
			
			if(!ArrayUtils.isEmpty(resources)){
				for(Resource resource : resources){
					parserContext.getReaderContext().getReader().loadBeanDefinitions(resource);
				}
				
				parserContext.getReaderContext()
					.fireImportProcessed(parserContext.getReaderContext().getResource().toString(), 
						resources,parserContext.extractSource(element));
			}
			
			Framework.optionalPartLoaded(id, locations);
		}else{
			Framework.optionalPartNotLoaded(id, locations);
		}
	}

}
